package com.yzy.domain.strategy.service.rule.chain.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Component;

import com.google.common.base.Preconditions;

import com.yzy.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.yzy.domain.strategy.repository.IStrategyRepository;
import com.yzy.domain.strategy.service.armory.IStrategyDispatch;
import com.yzy.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.yzy.domain.strategy.service.rule.chain.ILogicChain;
import com.yzy.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.yzy.domain.strategy.service.rule.chain.factory.DefaultChainFactory.LogicModel;
import com.yzy.domain.strategy.service.rule.filter.ILogicFilter;
import com.yzy.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import com.yzy.types.common.Constants;
import com.yzy.types.common.Constants.RuleKey;


import lombok.extern.slf4j.Slf4j;

/**
 * @author yangzhenyu05 <yangzhenyu05@kuaishou.com>
 * Created on 2024-01-14
 * @description 【抽奖前规则】根据抽奖权重返回可抽奖范围KEY
 */
@Slf4j
@Component(RuleKey.RULE_WEIGHT_KEY)
public class RuleWeightLogicChain extends AbstractLogicChain {
    @Resource
    private IStrategyRepository repository;

    @Resource
    protected IStrategyDispatch strategyDispatch;

    public Long userScore = 4500L;

    /**
     * 权重责任链过滤；
     * 1. 权重规则格式；4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
     * 2. 解析数据格式；判断哪个范围符合用户的特定抽奖范围
     */


    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
        // 1. 根据用户ID查询用户抽奖消耗的积分值，先写死为固定的值。后续需要从数据库中查询。
        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);
        if (ObjectUtils.isEmpty(analyticalValueGroup)) {
            log.warn(
                    "抽奖责任链-权重告警【策略配置权重，但ruleValue未配置相应值】 userId: {} strategyId: {} ruleModel: {}",
                    userId, strategyId, ruleModel());
            return next().logic(userId, strategyId);
        }
        // 2. 转化Key值，并默认排序
        ArrayList<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(analyticalSortedKeys);
        // 3. 找出最小符合值
        Long nextValue = analyticalSortedKeys.stream()
                .sorted(Comparator.reverseOrder())
                .filter(analyticalSortedKeyValue -> userScore >= analyticalSortedKeyValue)
                .findFirst()
                .orElse(null);
        // 4. 执行权重抽奖
        if (ObjectUtils.isNotEmpty(nextValue)) {
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValueGroup.get(nextValue));
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId,
                    ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }
        // 5. 过滤其他责任链
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return next().logic(userId, strategyId);
    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroups) {
            if (ObjectUtils.isEmpty(ruleValueKey)) {
                return ruleValueMap;
            }
            String[] parts = ruleValueKey.split(Constants.COLON);
            Preconditions.checkArgument(parts.length != NumberUtils.INTEGER_TWO,
                    "rule_weight rule_rule invalid input format" + ruleValueKey);
            ruleValueMap.put(Long.valueOf(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }

    @Override
    protected String ruleModel() {
        return LogicModel.RULE_WEIGHT.getCode();
    }
}
